<template>
  <el-container style="width: 100%; height: 100%">
    <el-header height="50px" class="header" style="background: #ffffff; z-index: 2">
      <!--左侧平台logo与平台名称-->
      <div class="logo" @click="goHome">
        <img :src="systemLogoUrl" class="system-logo" alt="系统LOGO" />
        {{ platformName }}
      </div>
      <!--登出图标-->
      <div class="logout-icon" @click="logoutConfirm">
        <font-awesome-icon :icon="['fas', 'sign-out-alt']" class="awesome"> </font-awesome-icon>
      </div>
      <!-- 全屏按钮 -->
      <div class="full-screen" @click="screenFull">
        <i class="el-icon-full-screen"></i>
      </div>
      <!--登录按钮-->
      <router-link v-if="!userID" :to="{ name: 'login' }" class="login-text">登录</router-link>
      <!--用户头像与用户名-->
      <el-tooltip v-else effect="light" placement="bottom-end" style="float: right" trigger="hover">
        <div slot="content" style="text-align: center">
          <el-button size="mini" type="text" @click="updatePersonInfo">个人信息</el-button>
          <hr align="center" width="50" color="#987cb9" SIZE="1" />
          <el-button size="mini" type="text" @click="updatePassword">修改密码</el-button>
        </div>
        <div class="reference">
          <span class="username">{{ userName }}</span>
          <div class="head-img" v-if="userHeadImgUrl">
            <img :src="userHeadImgUrl" class="header-user-headimg" alt="用户头像" />
          </div>
          <span class="username">{{ institutionName }}({{ roleName }})</span>
        </div>
      </el-tooltip>
    </el-header>
    <el-container>
      <el-aside :width="sideWidth" class="side-bar">
        <div class="footer1">
          <div v-if="isFold" size="mini" class="button-fold" @click="foldAside">
            <i class="el-icon-arrow-right"></i>
          </div>
          <div v-else size="mini" class="button-fold" @click="foldAside">
            <i class="el-icon-arrow-left"></i>
          </div>
        </div>
        <div class="content">
          <el-menu :default-active="nowRoute" :router="true" background-color="#545c64" text-color="#ffffff"
            @select="handlePermissionSelect" :collapse="isFold" active-text-color="#266EFF">
            <el-submenu v-for="(role, rIndex) in permissionGroupList" :key="rIndex" :index="'' + rIndex">
              <template slot="title">
                <font-awesome-icon prefix="far" :icon="role.icon" class="awesome"></font-awesome-icon>
                <span>{{ role.name }}</span>
              </template>
              <template v-for="(permission, pIndex) in role.permissionList">
                <el-menu-item v-if="permission.route !== '/'" :index="permission.route" :key="'' + rIndex + '-' + pIndex"
                  style="min-width: 179px">
                  <font-awesome-icon prefix="far" :icon="permission.icon" class="awesome"></font-awesome-icon>
                  {{ permission.name }}
                </el-menu-item>
              </template>
            </el-submenu>
          </el-menu>
        </div>
      </el-aside>
      <el-main class="main">
        <router-view></router-view>
      </el-main>
    </el-container>
    <!-- <el-footer class="footer">
      <div style="display: flex; justify-content: center; align-items: center">
        <div style="color: #888888;">
          © FOREMOST. 上海爱可及医疗科技有限公司 V1.0
        </div>
      </div>
    </el-footer> -->
  </el-container>
</template>

<script>
export default {
  name: 'LayoutMain',

  data() {
    return {
      // 系统logo地址
      systemLogoUrl: 'http://www.aikeji.top:50005/_uploads/PHOTO/1722578117626.png',
      // 用户操作监听
      checkTimeoutInterval: null,
      // 平台名称
      platformName: '',
      // 用户信息
      userData: null,
      // 侧边栏是否折叠
      isFold: false,
      // 权限列表数据结构
      permissionGroupList: this.$store.state.permissionList,
      uArgs: this.$store.getters.getUArgs
    }
  },

  mounted() {
    // 是否已登录
    if (!this.userID) {
      this.$message.info('请先登录')
      this.logout()
      return
    }
    this.__init()
    this.getPlatform()
    this.screenFull()
  },

  methods: {
    screenFull() {
      if (
        !document.fullscreenElement &&
        !document.msFullscreenElement &&
        !document.mozFullScreenElement &&
        !document.webkitFullscreenElement
      ) {
        let docElm = document.documentElement
        if (docElm.requestFullscreen) {
          docElm.requestFullscreen()
        } else if (docElm.msRequestFullscreen) {
          // IE
          docElm = document.body // overwrite the element (for IE)
          docElm.msRequestFullscreen()
        } else if (docElm.mozRequestFullScreen) {
          // 火狐
          docElm.mozRequestFullScreen()
        } else if (docElm.webkitRequestFullScreen) {
          // 谷歌
          docElm.webkitRequestFullScreen()
        }
      } else if (document.exitFullscreen) {
        document.exitFullscreen()
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen()
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen()
      } else if (document.webkitCancelFullScreen) {
        document.webkitCancelFullScreen()
      }
    },
    goHome() {
      this.$router.push(this.permissionGroupList[0].permissionList[0].route)
    },
    async getPlatform() {
      await this.$axios({
        // 详见 axios 请求配置项
        method: 'GET',
        url: '/institutions/platform',
        headers: {
          authorization: this.$store.getters.getAuthorization
        }
      }).then(res => {
        // 请求失败
        if (res.data.code !== 200) {
          throw new Error(res.data)
        }
        // 请求成功
        const result = res.data.data
        this.platformName = result.name
      })
    },
    __init() {
      const that = this
      this.$store.commit('setPropertyGeneral', {
        key: 'lastTime',
        value: `${new Date().getTime()}`
      })

      window.onload = function () {
        window.document.onmousedown = function () {
          that.$store.commit('setPropertyGeneral', {
            key: 'lastTime',
            value: `${new Date().getTime()}`
          })
        }
      }

      // 无操作一段时间后登出
      const checkTimeout = function () {
        const currentTime = new Date().getTime() // 更新当前时间
        const { lastTime } = that.$store.state
        const timeOut = 48 * 60 * 60 * 1000 // 超时时间为48h
        console.log('no operation time', currentTime - lastTime)

        if (currentTime - lastTime > timeOut) {
          // 判断是否超时
          if (that.checkTimeoutInterval) {
            clearInterval(that.checkTimeoutInterval)
            that.checkTimeoutInterval = null
          }
          that.logout()
        }
      }
      this.checkTimeoutInterval = window.setInterval(checkTimeout, 30000) // 30s 检查一次
    },
    // 登出确认
    logoutConfirm() {
      this.$confirm('即将退出登录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios({
          method: 'PUT',
          url: '/logout',
          headers: {
            authorization: this.$store.getters.getAuthorization
          }
        })

        this.logout()
      })
    },
    // 登出操作
    logout() {
      if (this.checkTimeoutInterval) {
        clearInterval(this.checkTimeoutInterval)
        this.checkTimeoutInterval = null
      }
      this.$store.commit('setPropertyGeneral', {
        key: 'authorization',
        value: ''
      })
      this.$store.commit('setUser', { phone: null })
      this.$router.push('/login')
    },
    foldAside() {
      this.isFold = !this.isFold
    },
    // 跳转个人信息编辑页面
    updatePersonInfo() {
      this.$store.commit('setUArgs', {
        isPlatformManage: this.uArgs.isPlatformManage,
        isAddNew: 0,
        userId: this.$store.state.user.id,
        institutionId: this.$store.state.institution.id
      })
      this.$router.push('/editPersonalInfo')
    },
    // 跳转修改密码页面
    updatePassword() {
      this.$router.push('/ChangePassword')
    },
    // 权限选择监听
    handlePermissionSelect(val) {
      console.log('handlePermissionSelect-val', val)
      if (val === '/samplesGallery') {
        window.open('http://10.1.192.128:9001/index/')
      } else {
        this.$store.commit('setPropertyGeneral', { key: 'nowRoute', value: val })
      }
    }
  },

  computed: {
    // 用户ID
    userID() {
      return this.$store.state.user.id
    },
    // 用户名
    userName() {
      return this.$store.state.user.name
    },
    // 角色
    roleName() {
      return this.$store.state.user.roleName
    },
    //医院名
    institutionName() {
      return this.$store.state.institution.name
    },
    // 用户头像图片链接
    userHeadImgUrl() {
      if (this.$store.state.user.headImgUrl) {
        return process.env.VUE_APP_ImageServiceURL + this.$store.state.user.headImgUrl
      }
      return '/images/doctor.png'
    },
    // 侧边栏宽度
    sideWidth() {
      return this.isFold ? '64px' : '180px'
    },
    // 默认激活权限项
    nowRoute() {
      console.log('nowRoute', this.$store.state.nowRoute)
      return this.$store.state.nowRoute
    }
  },
  destroyed() {
    if (this.checkTimeoutInterval) {
      clearInterval(this.checkTimeoutInterval)
      this.checkTimeoutInterval = null
    }
  }
}
</script>

<style scoped>
@media screen and (max-width: 1000px) {}

.main {
  width: calc(100% - 180px);
  height: 100%;
  min-height: 500px;
  padding: 0;
}

.main .user-info {
  float: right;
}

.logo {
  height: 50px;
  width: auto;
  font-size: 18px;
  color: #266eff;
  line-height: 50px;
  float: left;
  cursor: pointer;
}

.logo img {
  vertical-align: middle;
}

.header {
  box-shadow: 0 1px 3px 1px rgba(26, 26, 26, 0.2);
  vertical-align: middle;
  margin-top: 0;
}

.head-img {
  width: 32px;
  height: 32px;
  margin-top: 9px;
  float: right;
}

.login-text {
  float: right;
  line-height: 50px;
  margin-left: 5px;
}

.username {
  margin-left: 10px;
  line-height: 50px;
  float: right;
}

.logout-icon {
  height: 50px;
  margin-left: 25px;
  line-height: 50px;
  float: right;
  cursor: pointer;
}

.side-bar {
  transition: width 0.2s ease-in-out 0s;
  background-color: #545c64;
  font-size: 14px;
  position: relative;
  overflow-y: hidden;
  overflow-x: hidden;
  min-height: 835px;
  max-height: 835px;
}

svg.awesome {
  height: 18px;
  width: 18px;
}

.footer {
  height: 50px !important;
  line-height: 50px;
  -webkit-box-flex: 0;
  -ms-flex: 0 0 auto;
  flex: 0 0 auto;
  background-color: #f2f2f2;
}

.reference {
  width: auto;
  float: right;
}

.content {
  min-height: calc(92vh - 70px);
  height: calc(100% - 32px);
  overflow-y: auto;
  overflow-x: hidden;
  position: absolute;
}

.footer1 {
  overflow: visible;
  /* position: absolute; */
  left: 192px;
  top: 40%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 30px;
  font-size: 25px;
  color: #266eff;
  z-index: 9999;
}

.button-fold {
  float: right;
  border: none;
}

.el-menu {
  border-right: none;
}

.full-screen {
  float: right;
  font-size: 25px;
  line-height: 45px;
  margin-left: 15px;
  cursor: pointer;
}
</style>
